package com.parking.bang.rpc.core.client;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

import com.parking.bang.rpc.serialize.base.RPCSerializeProtocol;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class RPCClientInitializeTask implements Callable<Boolean> {
	private EventLoopGroup eventLoopGroup = null;
	private InetSocketAddress serverAddress = null;
	private RPCSerializeProtocol rpcSerializeProtocol;

	public RPCClientInitializeTask(EventLoopGroup eventLoopGroup, InetSocketAddress serverAddress,
			RPCSerializeProtocol rpcSerializeProtocol) {
		this.eventLoopGroup = eventLoopGroup;
		this.serverAddress = serverAddress;
		this.rpcSerializeProtocol = rpcSerializeProtocol;
	}

	public Boolean call() throws Exception {
		Bootstrap b = new Bootstrap();
		b.group(eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);
		b.handler(new RPCClientChannelInitializer().setProtocol(rpcSerializeProtocol));

		ChannelFuture channelFuture = b.connect(serverAddress);
		channelFuture.addListener(new ChannelFutureListener() {
			public void operationComplete(final ChannelFuture channelFuture) throws Exception {
				if (channelFuture.isSuccess()) {
					MessageSendHandler handler = channelFuture.channel().pipeline().get(MessageSendHandler.class);
					RPCServerLoader.getInstance().setMessageSendHandler(handler);
				}
			}
		});
		return Boolean.TRUE;
	}
}
